package org.springblade.modules.restaurant.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.constant.RestaurantConstant;
import org.springblade.modules.restaurant.dto.CommodityRecordDTO;
import org.springblade.modules.restaurant.entity.CommodityRecord;
import org.springblade.modules.restaurant.entity.CommodityRecordRelation;
import org.springblade.modules.restaurant.service.IBaseConfigService;
import org.springblade.modules.restaurant.service.ICommodityRecordRelationService;
import org.springblade.modules.restaurant.service.ICommodityRecordService;
import org.springblade.modules.restaurant.vo.CommodityRecordVO;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author harry
 * @公众号 Harry技术
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/restaurant/commodity")
@Tag(name = "API - 货物采购记录")
public class ApiCommodityController {

	private ICommodityRecordService commodityRecordService;
	private ICommodityRecordRelationService commodityRecordRelationService;
	private final IBaseConfigService baseConfigService;

	/**
	 * 分页 货物采购记录
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入commodityRecord")
	public R<IPage<CommodityRecord>> list(@ParameterObject CommodityRecordVO commodityRecord, @ParameterObject Query query) {
		String startTime = commodityRecord.getStartTime();
		String endTime = commodityRecord.getEndTime();

		LambdaQueryWrapper<CommodityRecord> wrapper = Wrappers.lambdaQuery(commodityRecord);
		if (StrUtil.isNotBlank(startTime) && StrUtil.isNotBlank(endTime)) {
			startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(DateUtil.parse(startTime, DatePattern.NORM_DATE_PATTERN)));
			endTime = DateUtil.formatDateTime(DateUtil.endOfDay(DateUtil.parse(endTime, DatePattern.NORM_DATE_PATTERN)));
		} else {
			Date now = DateUtil.date();
			// 获取今天开始时间
			startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(now));
			// 获取当前时间
			endTime = DateUtil.formatDateTime(now);
		}
		wrapper.between(CommodityRecord::getCreateTime, startTime, endTime);
		wrapper.orderByDesc(CommodityRecord::getCreateTime);

		IPage<CommodityRecord> pages = commodityRecordService.page(Condition.getPage(query), wrapper);
		return R.data(pages);
	}

	/**
	 * 详情
	 */
	@GetMapping("/getDetail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入commodityRecord")
	public R<CommodityRecordVO> getDetail(CommodityRecord commodityRecord) {
		CommodityRecordVO res = new CommodityRecordVO();

		CommodityRecord detail = commodityRecordService.getOne(Condition.getQueryWrapper(commodityRecord));
		BeanUtil.copyProperties(detail, res);

		List<CommodityRecordRelation> infos = commodityRecordRelationService.list(Wrappers.lambdaQuery(new CommodityRecordRelation()).eq(CommodityRecordRelation::getCommodityRecordId, detail.getId()));

		res.setInfo(infos);
		return R.data(res);
	}

	/**
	 * 删除采购单
	 *
	 * @param ids
	 * @return
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		commodityRecordService.deleteLogic(Func.toLongList(ids));
		return R.status(commodityRecordRelationService.remove(Wrappers.lambdaQuery(CommodityRecordRelation.class)
			.in(CommodityRecordRelation::getCommodityRecordId, Func.toLongList(ids))));
	}

	/**
	 * 删除明细
	 */
	@PostMapping("/delDetailById")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R delDetailById(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		// 删除采购单明细 并 更新采购单摘要
		boolean res = commodityRecordService.delDetail(Func.toLongList(ids));
		return R.status(res);
	}

	/**
	 * 更新明细数量
	 */
	@PostMapping("/updateDetailNumberById/{id}")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "更新明细数量", description = "传入id(明细ID),number")
	public R updateDetailNumberById(@PathVariable Long id, Integer number) {
		CommodityRecordRelation commodityRecordRelation = commodityRecordRelationService.getById(id);
		if (commodityRecordRelation == null) {
			log.error("采购单明细不存在,id:{}", id);
			return R.fail("采购单明细不存在");
		}
		if (number < 0) {
			return R.fail("数量不能小于0");
		}
		commodityRecordRelation.setNumber(number);
		return R.status(commodityRecordRelationService.updateById(commodityRecordRelation));

	}

	/**
	 * 保存采购记录
	 */
	@ApiLog(value = "保存采购记录")
	@PostMapping("/saveCommodity")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "保存采购记录", description = "传入commodityRecord")
	public R saveCommodity(@Valid @RequestBody CommodityRecordDTO commodityRecord) {

		BladeUser user = SecureUtil.getUser();
		commodityRecord.setUserId(user.getUserId());
		commodityRecord.setUserName(user.getUserName());

		// 检查下单时间是否已截至
		String time = baseConfigService.getValueByKey(RestaurantConstant.PROCUREMENT_DEADLINE);
		DateTime data = DateUtil.date();
		DateTime dateTime = DateUtil.parse(time);
		if (data.isAfter(dateTime)) {
			return R.fail("今日采购时间已截至:" + time + ",请明天记得早点来哦");
		}

		return R.status(commodityRecordService.saveCommodity(commodityRecord));
	}

	/**
	 * 更新状态
	 */
	@ApiLog(value = "更新采购(审核)状态")
	@PostMapping("/statusUpdate/{id}")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "更新状态", description = "传入id(采购记录ID),status")
	public R statusUpdate(@PathVariable Long id, Integer status) {
		return R.status(commodityRecordService.statusUpdate(id, status));
	}
}
